package com.xcode.example.modules.common.controller;

import com.xcode.example.base.BaseController;
import com.xcode.example.common.result.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 统一操作controller，如文件上传、下载等
 * @author Administrator
 */
@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {
    /**
     * 图片批量上传接口
     * @return 页面地址
     */
    @RequestMapping("/ajaxMultiImageUpload")
    @ResponseBody
    public AjaxResult ajaxMultiImageUpload(HttpServletRequest request) {
        if (request instanceof MultipartRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("file");
            if (files.size() > 0) {
                AjaxResult result = AjaxResult.success();
                List<String> imgUrls = new ArrayList<>();
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
                    // 获取文件扩展名
                    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                    //如果文件不是图片，则不上传
                    if (!"jpg".equalsIgnoreCase(ext) && !"jpeg".equalsIgnoreCase(ext)
                            && !"png".equalsIgnoreCase(ext) && !"gif".equalsIgnoreCase(ext)
                            && !"bmp".equalsIgnoreCase(ext)) {
                        continue;
                    }

                    String imgUrl = uploadFile(file);
                    if (StringUtils.isNotBlank(imgUrl)) {
                        imgUrls.add(imgUrl);
                    }
                }

                result.put("imgUrls", imgUrls);
                return result;
            } else {
                return AjaxResult.error("未选择文件");
            }
        }
        return AjaxResult.error("未选择文件");
    }

    /**
     * 文件上传接口
     * @return 页面地址
     */
    @RequestMapping("/ajaxFileUpload")
    @ResponseBody
    public AjaxResult ajaxFileUpload(MultipartFile file) {
        if (file != null && file.getSize() > 0) {
            String filePath = uploadFile(file);
            if (StringUtils.isNotBlank(filePath)) {
                return AjaxResult.success().put("filePath", filePath);
            } else {
                return AjaxResult.error("文件上传失败");
            }
        }
        return AjaxResult.error("未选择文件");
    }

}
